import React, { Component } from 'react';
import styles from './BpmnEditor.less';
import { Button } from 'antd';
import { readMockBPMNFile } from '@/services/bpmn';

// 这个viewer只是看的
// import BpmnViewer from 'bpmn-js';

// 引入建模的依赖
// import BpmnModeler from 'bpmn-js/lib/Modeler';

// 添加了右侧的属性面板  type: camunda
import propertiesPanelModule from 'bpmn-js-properties-panel';
import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda';
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda';

// 添加了右侧的属性面板  type: bpmn
// import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/bpmn';

// import magicPropertiesProviderModule from './customModeler/properties';
// import magicModdleDescriptor from './customModeler/properties/descriptors/magic';

import { CustomModeler } from './customModeler';
// 翻译
import customTranslate from './customTranslate/customTranslate';

export default class BpmnEditor extends Component {
  constructor(props) {
    super(props);

    this.state = {
      modeler: null,
    };

    this.containerRef = React.createRef();
  }

  componentDidMount() {
    const customTranslateModule = {
      translate: ['value', customTranslate],
    };

    // 建模
    this.bpmnModeler = new CustomModeler({
      container: this.containerRef.current,
      // 添加控制板
      propertiesPanel: {
        parent: '#js-properties-panel',
      },
      additionalModules: [
        // 右边的属性栏
        propertiesProviderModule,
        propertiesPanelModule,
        customTranslateModule,
        // magicPropertiesProviderModule,
      ],
      moddleExtensions: {
        // 解开下方代码，使用详细的模型
        camunda: camundaModdleDescriptor,
        // magic: magicModdleDescriptor,
      },
    });

    // 创建新的图
    this.bpmnModeler.createDiagram();

    this.bpmnModeler.on('selection.changed', (e) => {
      if (e.newSelection.length > 0) {
        console.log(e.newSelection[0]);
      }
    });

    this.setState({ modeler: this.bpmnModeler });
  }

  componentDidUpdate(prevProps, prevState) {
    const { props, state } = this;

    const currentXML = props.diagramXML || state.diagramXML;

    const previousXML = prevProps.diagramXML || prevState.diagramXML;

    if (currentXML && currentXML !== previousXML) {
      return this.displayDiagram(currentXML);
    }
  }

  async displayDiagram(diagramXML) {
    try {
      const result = await this.bpmnModeler.importXML(diagramXML);
      const { warnings } = result;
      console.log(warnings);
    } catch (err) {
      console.log(err.message, err.warnings);
    }
  }

  componentWillUnmount() {
    // this.bpmnModeler.destroy();
  }

  render() {
    const { modeler } = this.state;
    return (
      <div className={styles.bpmnEditor}>
        <div className={styles.actionBar}>
          <Button onClick={this.handleDownloadXml}>导出XML</Button>
          <Button onClick={this.handlePrintXml}>打印</Button>
          <Button onClick={this.handleReadXml}>Read</Button>
        </div>
        <div className={styles.wrapper} ref={this.containerRef}></div>
        <div id="js-properties-panel" className={styles.propertiesPanel}></div>
        {/* <RightPanel modeler={modeler} /> */}
      </div>
    );
  }

  // 下载xml/svg
  //  @param  type  类型  svg / xml
  //  @param  data  数据
  //  @param  name  文件名称
  download = (type, data, name) => {
    let dataTrack = '';
    const a = document.createElement('a');

    switch (type) {
      case 'xml':
        dataTrack = 'bpmn';
        break;
      case 'svg':
        dataTrack = 'svg';
        break;
      default:
        break;
    }

    a.setAttribute('href', `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(data)}`);
    a.setAttribute('target', '_blank');
    a.setAttribute('dataTrack', `diagram:download-${dataTrack}`);
    a.setAttribute('download', name || `diagram.${dataTrack}`);

    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  // 下载 XML 格式
  handleDownloadXml = async () => {
    try {
      const result = await this.bpmnModeler.saveXML({ format: true });
      const { xml } = result;
      this.download('xml', xml);
    } catch (err) {
      console.log(err);
    }
  };

  handlePrintXml = async () => {
    const result = await this.bpmnModeler.saveXML({ format: false });
    const { xml } = result;
    console.log(xml);
  };

  handleReadXml = async () => {
    const result = await readMockBPMNFile();
    console.log(result);
    this.bpmnModeler.importXML(result.xml);
  };
}
